const fs = require('fs');
const path = require('path');
const { loadEnv } = require('vite');
const { launchCli } = require('../script/autoOpenMiniCli.js');

//合并tabBar让配置
function handleTabBarConfig(options, bundle) {
  if (!bundle['app.json']) return;
  // 读取tabbar-config.json
  let tbsStr = fs.readFileSync(`${process.cwd()}/src/tabbar-config.json`, 'utf-8');
  let tbsJson = JSON.parse(tbsStr);
  // 读取app.json
  let appJson = JSON.parse(bundle['app.json'].source);
  appJson.tabBar = appJson.tabBar || {};
  // 合并
  appJson.tabBar = { ...tbsJson, ...appJson.tabBar };
  // 写入app.json
  fs.writeFileSync(`${options.dir}/app.json`, JSON.stringify(appJson, null, 2));
}

//将appid写入到打包后的project.config.json中
function handleProjectConfig(options, bundle, env) {
  if (!bundle['project.config.json']) return;
  // 读取project.config.json
  let projectJson = JSON.parse(bundle['project.config.json'].source);
  if (env.VITE_WX_APPID) {
    projectJson.appid = env.VITE_WX_APPID;
  }
  // 写入project.config.json
  fs.writeFileSync(path.resolve(options.dir, './project.config.json'), JSON.stringify(projectJson, null, 2));
}

//将对应环境的ciKey拷贝到dist中
function copyCiKey(options, bundle, env) {
  let cikeyPath = path.resolve(process.cwd(), `./wx-ci-key/private.${env.VITE_WX_APPID}.key`);
  let wxCiKey = fs.readFileSync(cikeyPath, 'utf-8');
  let wxCiKeyDistPath = path.resolve(options.dir, './private.wx-ci.key');
  fs.writeFileSync(wxCiKeyDistPath, wxCiKey);
  let wxciparams = {
    cikey: wxCiKeyDistPath,
    appid: env.VITE_WX_APPID,
    projectPath: options.dir,
  };
  fs.writeFileSync(path.resolve(process.cwd(), './wx-ci-params.json'), JSON.stringify(wxciparams, null, 2));
}

export default createPlugin = ({ mode }) => {
  let hasBound = false;
  const env = loadEnv(mode, path.resolve(__dirname, '../'));
  return {
    name: 'tll-plugin',
    enforce: 'post',
    writeBundle(options, bundle) {
      handleTabBarConfig(options, bundle);
      handleProjectConfig(options, bundle, env);
      try {
          copyCiKey.call(this, options, bundle, env);
      } catch (error) {
        console.log(error);
      }
      //自动打开小程序开发者工具
      if (!hasBound && env.VITE_USER_NODE_ENV!='production') {
        hasBound = true;
        launchCli({ projectPath: options.dir, env });
      }
    },
  };
};
